package top.drinyeit.nongmao.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.citywheel.CityPickerView;

import top.drinyeit.nongmao.R;
import top.drinyeit.nongmao.base.BaseActivity;
import top.drinyeit.nongmao.dialog.CenterDialog;
import top.drinyeit.nongmao.model.AddressDetailJsonBean;
import top.drinyeit.nongmao.presenter.EditAddressPresenter;
import top.drinyeit.nongmao.util.Validator;

/**
 * Created by bigHead on 2017/11/15.
 */

public class EditAddressActivity extends BaseActivity {

    CityPickerView cityPicker;
    private TextView consignee_name,consignee_phone,place,detail;
    private RelativeLayout default_show;//设置默认
    private TextView save_btn;//保存按钮
    private TextView delete_btn;//删除按钮
    private TextView number;
    private AddressDetailJsonBean addressDetailJsonBean;

    private int addressId;//地址编号
    private String consigneeName,consigneePhone,addressDetail;

    private CenterDialog centerDialog_delete;

    private EditAddressPresenter editAddressPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_newaddress);

        setToolbar2(true,"编辑地址");
        centerDialog_delete = new CenterDialog(this,R.layout.dialog_center);

        consignee_name = findViewById(R.id.consignee_name);
        consignee_phone = findViewById(R.id.consignee_phone);
        place = findViewById(R.id.place);
        detail = findViewById(R.id.detail);
        number = findViewById(R.id.number);

        default_show = (RelativeLayout) findViewById(R.id.default_show);
        save_btn = (TextView) findViewById(R.id.save_btn);
        delete_btn = (TextView) findViewById(R.id.delete_btn);

        editAddressPresenter = new EditAddressPresenter(this);

        initIntent();
        init();
    }

    public void initIntent(){
        if (getIntent() == null){
            showToast("未知错误，请重新操作");
            return;
        }
        Bundle bundle = getIntent().getExtras();
        addressId = bundle.getInt("address_id");
        consigneeName = bundle.getString("consignee_name");
        consigneePhone = bundle.getString("consignee_phone");
        addressDetail = bundle.getString("address_detail");
        addressDetailJsonBean=new Gson().fromJson(addressDetail,new TypeToken<AddressDetailJsonBean>(){}.getType());



        consignee_name.setText(consigneeName);
        consignee_phone.setText(consigneePhone);
        place.setText(addressDetailJsonBean.getProvince() + addressDetailJsonBean.getCity() + addressDetailJsonBean.getRegion());
        place.setTextColor(ContextCompat.getColor(this,R.color.text_black));

        detail.setText(addressDetailJsonBean.getDetail());
        number.setText(addressDetailJsonBean.getDetail().length() + "");

    }

    @Override
    public void init() {
        default_show.setVisibility(View.GONE);
        save_btn.setVisibility(View.VISIBLE);
        delete_btn.setVisibility(View.GONE);

        //选择地址
        place.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                if (cityPicker == null) {
                    CityConfig cityConfig = new CityConfig.Builder(EditAddressActivity.this)
                            .textSize(18)//（滚轮文字的大小，int 类型，默认为18）
                            .title("地区选择")//（选择器标题，默认为“选择地区”）
                            .titleBackgroundColor("#ffffff")//（标题栏背景，默认为灰色，#C7C7C7）
                            .titleTextColor("#333333")//(标题文字颜色，默认为 #E9E9E9)
                            .confirTextColor("#666666")//（确认按钮字体颜色，默认为系统的colorPrimary颜色值）
                            .cancelTextColor("#666666")//（取消按钮字体颜色，默认为系统的colorPrimary颜色值）
                            .province(addressDetailJsonBean.getProvince())//（默认的显示省份，显示选择器后直接定位的item位置）
                            .city(addressDetailJsonBean.getCity().replace("市",""))//（默认的显示市，显示选择器后直接定位的item位置）
                            .district(addressDetailJsonBean.getRegion())//（默认的显示区，显示选择器后直接定位的item位置）
                            .textColor("#333333")//（滚轮文字的颜色 ，int 类型，默认为0xFF585858）
                            .provinceCyclic(true)//（省份的滚轮是否循环滚动）
                            .cityCyclic(false)//（市的滚轮是否循环滚动）
                            .districtCyclic(false)//（区的滚轮是否循环滚动）
                            .visibleItemsCount(7)//（滚轮显示的item个数，int 类型，默认为5个）
                            .itemPadding(10)//（滚轮item间距，默认为5dp）
                            .setCityInfoType(CityConfig.CityInfoType.BASE) //BASE:只包含省市区名称; DETAIL:包含详细的经纬度、code、省市区数据名称等数据
                            .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)
                            .build();
                    cityPicker = new CityPickerView(cityConfig);
                    //监听方法，获取地址选择结果
                    cityPicker.setOnCityItemClickListener(new CityPickerView.OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                            if (addressDetailJsonBean == null) {
                                if (district == null){
                                    addressDetailJsonBean = new AddressDetailJsonBean(province.getName(), city.getName() + "市", "", "");
                                }else {
                                    addressDetailJsonBean = new AddressDetailJsonBean(province.getName(), city.getName() + "市", "", district.getName());
                                }
                            } else {
                                addressDetailJsonBean.setProvince(province.getName());
                                addressDetailJsonBean.setCity(city.getName() + "市");
                                if (district == null){
                                    addressDetailJsonBean.setRegion("");
                                }else {
                                    addressDetailJsonBean.setRegion(district.getName());
                                }

                            }
                            place.setText(province.getName() + city.getName() + "市" + (district == null ? "": district.getName()));
                            place.setTextColor(ContextCompat.getColor(EditAddressActivity.this,R.color.text_black));

                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                }
                cityPicker.show();
            }
        });

        //保存
        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (consignee_name.getText().length() < 1){
                    showToast("收货人不能为空");
                    return;
                }
                if (!Validator.isMobile(consignee_phone.getText().toString())){
                    showToast("请填写正确的手机号");
                    return;
                }
                if (addressDetailJsonBean ==null){
                    showToast("请选择所在地");
                    return;
                }
                if (detail.getText().length() < 2){
                    showToast("请填写详细地址");
                    return;
                }else {
                    addressDetailJsonBean.setDetail(detail.getText().toString());
                }
                editAddressPresenter.editAdd(addressId,consignee_name.getText().toString(),consignee_phone.getText().toString(),new Gson().toJson(addressDetailJsonBean));
            }
        });

        //删除按钮弹窗
        delete_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                centerDialog_delete.show();
                TextView dialog_text =  centerDialog_delete.findViewById(R.id.dialog_text);
                dialog_text.setText("确定要删除该地址吗");
                TextView dialog_sure = centerDialog_delete.findViewById(R.id.dialog_sure);
                dialog_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(view.getContext(),"确认",Toast.LENGTH_SHORT).show();
                        centerDialog_delete.dismiss();
                    }
                });
                TextView dialog_cancel = centerDialog_delete.findViewById(R.id.dialog_cancel);
                dialog_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        centerDialog_delete.dismiss();
                    }
                });

            }
        });
        detail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                number.setText(s.length()+ "");
            }
        });

    }


}
